/*
 * Copyright (c) 2020, 2023, 3044483124@qq.com All rights reserved.
 *
 */
package cn.itcast;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * <p>Project: jdbc - DruidUtils
 * <p>Powered by jiangbo On 2023-02-14
 * 17:18:07
 * <p>Created by IntelliJ IDEA
 *
 * @author jiangbo [3044483124@qq.com]
 * @version 1.0
 * @since 8/17
 */
//Druid工具类
public class DruidUtils {
    //1.私有构造
    public DruidUtils(){}
    //2.定义DataSource静态变量
    private static DataSource dataSource;
    //3.定义static静态代码块加载配置文件和数据连接池对象
    static{
//加载配置文件
        try {
//加载配置文件
          //prop.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properti es"));
//获取连接池对象
          //dataSource= DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //4.提供获取数据库连接的方法
    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn=dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //5.提供获取数据库连接池的方法
    public static DataSource getDataSource(){
        return dataSource;
    }
    //6.释放资源
    public static void close(Connection conn, Statement st, ResultSet rs){
        if(conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st !=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection conn, Statement st){
        close(conn,st,null);
    }
}


